package com.viethp.mt.activities;

import java.util.ArrayList;

import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.viethp.mt.adapters.OItemAdapter;
import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.customactivities.ATabNearByGroup;
import com.viethp.mt.objects.GetPostListResponse;
import com.viethp.mt.objects.OItem;
//import com.viethp.mt.objects.SignUpResponse;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class AGroupList extends Activity implements OnClickListener,
		OnItemClickListener {

	private static final String ITEM_ID = "id";
	// private static final String ITEM_USER_ID = "user_id";
	// private static final String ITEM_USERNAME = "username";
	private static final String ITEM_TITLE = "title";
	private static final String ITEM_DESCRIPTION = "description";
	private static final String ITEM_EXP = "expired";
	private static final String ITEM_PRICE = "price";
	private static final String ITEM_LON = "longitude";
	private static final String ITEM_LAT = "latitude";
	private static final String ITEM_IMG_LINK = "imgLink";
	private static final String ITEM_MAX_BUDGET = "max_budget";
	private static final String ITEM_TOTAL_BIDDER = "total_bidder";

	private Button btn_search, btn_refesh, btn_map;
	// private Button btn_asearch;
	private ListView lv_items;
	private ArrayList<OItem> list_Oitems;
	private OItemAdapter listoitemadapter;
	private ProgressDialog progressDialog;

	private ImageView img_search_category;
	public View footerView;
	private int totaPages, post_category, price_from, price_to;
	private int pages;
	private TextView txtshowmore, noResults, tv_category;
	private EditText edt_search, edt_from, edt_to;
	private String keyword;
	private String[] category_list_array = new String[] { "All",
			"Mobile phone", "Household electrical appliances", "Computer",
			"Telecommunications equipment" };

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_nearby_group_list);

		initComponents();
		addOnClickListener();
	}

	public void initComponents() {

		lv_items = (ListView) findViewById(R.id.lv_items_show);
		list_Oitems = new ArrayList<OItem>();

		// add
		footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.listfooter, null, false);
		lv_items.addFooterView(footerView);
		footerView.setVisibility(View.GONE);

		footerView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (pages < totaPages) {
					pages++;
					initData();

				}

			}
		});

		listoitemadapter = new OItemAdapter(this, R.layout.lv_items,
				list_Oitems);
		lv_items.setAdapter(listoitemadapter);
		lv_items.setOnItemClickListener(this);

		// add
		txtshowmore = (TextView) findViewById(R.id.idshow);
		noResults = (TextView) findViewById(R.id.tv_NoItems);
		noResults.setVisibility(View.GONE);

		tv_category = (TextView) findViewById(R.id.tv_category);
		img_search_category = (ImageView) findViewById(R.id.img_search_category);

		progressDialog = new ProgressDialog(getParent());
		progressDialog.setCancelable(false);

		totaPages = 1;
		pages = 1;
		post_category = 0;
		price_from = 0;
		price_to = 0;
		tv_category.setText(category_list_array[post_category]);

		// btn_asearch = (Button) findViewById(R.id.btn_search);
		// btn_asearch.setVisibility(View.GONE);
		btn_search = (Button) findViewById(R.id.btn_search);
		btn_refesh = (Button) findViewById(R.id.btn_refesh);
		btn_map = (Button) findViewById(R.id.btn_map);

		edt_search = (EditText) findViewById(R.id.edt_search);
		edt_from = (EditText) findViewById(R.id.edt_from);
		edt_to = (EditText) findViewById(R.id.edt_to);
		edt_from.setInputType(InputType.TYPE_CLASS_NUMBER);
		edt_to.setInputType(InputType.TYPE_CLASS_NUMBER);
		initData();
	}

	public void addOnClickListener() {
		// btn_asearch.setOnClickListener(this);
		btn_search.setOnClickListener(this);
		btn_refesh.setOnClickListener(this);
		btn_map.setOnClickListener(this);
		tv_category.setOnClickListener(this);
		img_search_category.setOnClickListener(this);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		// case R.id.btn_asearch:
		// Intent asearch = new
		// Intent(getApplicationContext(),AAdvancedSearch.class);
		// startActivity(asearch);
		// break;
		case R.id.btn_search:
			noResults.setVisibility(View.GONE);
			keyword = edt_search.getText().toString().trim();
			if (edt_from.getText().toString().trim().equals(""))
				price_from = 0;
			else
				price_from = Integer.parseInt(edt_from.getText().toString()
						.trim());
			if (edt_to.getText().toString().trim().equals(""))
				price_to = 0;
			else
				price_to = Integer.parseInt(edt_to.getText().toString().trim());
			// if (keyword.equals("")) {
			pages = 1;
			list_Oitems.removeAll(list_Oitems);
			// initData();
			// } else
			doSearch();
			break;
		case R.id.btn_map:
			// if(ATabNearByGroup.group.getcallbackSize()!=0){
			// ATabNearByGroup.group.callbackView();
			// }else{
			View view = ATabNearByGroup.group
					.getLocalActivityManager()
					.startActivity(
							"Map",
							new Intent(v.getContext(), AGroupMap.class)
									.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
					.getDecorView();
			ATabNearByGroup.group.replaceView(view);
			// }
			break;
		case R.id.btn_refesh:
			noResults.setVisibility(View.GONE);
			pages = 1;
			edt_search.setText("");
			edt_from.setText("");
			edt_to.setText("");
			post_category = 0;
			price_from = 0;
			price_to = 0;
			tv_category.setText(category_list_array[post_category]);
			list_Oitems.removeAll(list_Oitems);
			initData();
			break;
		case R.id.tv_category:
			DialogCategory();
			break;
		case R.id.img_search_category:
			DialogCategory();
			break;
		}

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
		// View view = ATabNearByGroup.group
		// .getLocalActivityManager()
		// .startActivity(
		// "AItemDetails",
		// new Intent(v.getContext(), AItemDetails.class)
		// .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
		// .getDecorView();
		// ATabNearByGroup.group.replaceView(view);

		Intent item_details = new Intent(getApplicationContext(),
				AItemDetails.class);
		item_details.putExtra(ITEM_ID,
				String.valueOf(this.list_Oitems.get(position).getId()));
		// item_details.putExtra(ITEM_USER_ID,
		// String.valueOf(this.list_Oitems.get(position).getUserId()));
		// item_details.putExtra(ITEM_USERNAME,
		// String.valueOf(this.list_Oitems.get(position).getUsername()));
		item_details.putExtra(ITEM_TITLE,
				String.valueOf(this.list_Oitems.get(position).getTitle()));
		item_details
				.putExtra(ITEM_DESCRIPTION, String.valueOf(this.list_Oitems
						.get(position).getDescription()));
		item_details.putExtra(ITEM_EXP,
				String.valueOf(this.list_Oitems.get(position).getExp()));
		item_details.putExtra(ITEM_PRICE,
				String.valueOf(this.list_Oitems.get(position).getPrice()));
		item_details
				.putExtra(ITEM_TOTAL_BIDDER, String.valueOf(this.list_Oitems
						.get(position).getTotalBidder()));
		item_details.putExtra(ITEM_MAX_BUDGET,
				String.valueOf(this.list_Oitems.get(position).getMaxBudget()));
		item_details.putExtra(ITEM_IMG_LINK,
				String.valueOf(this.list_Oitems.get(position).getImgLink()));
		item_details.putExtra(ITEM_LON,
				String.valueOf(this.list_Oitems.get(position).getLon()));
		item_details.putExtra(ITEM_LAT,
				String.valueOf(this.list_Oitems.get(position).getLat()));
		startActivity(item_details);

	}

	private void startCallService() {

		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callService();
				handler.sendMessage(message);

			}
		}).start();

	}

	private void startCallServiceSearch() {

		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callServiceSearch();
				handler.sendMessage(message);

			}
		}).start();

	}

	public void initData() {

		if (CommonHelper.isNetworkAvailable(this)) {
			startCallService();
		} else {
			CommonHelper.showWarning(this, getString(R.string.netstate));
		}

	}

	// private int callService() {
	//
	// demoData(10);
	// totaPages=5;
	// return GlobalVariables.ReOK;
	//
	// }

	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				GetPostListResponse response = (GetPostListResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(getParent(), response
							.getErrorCode().getErrMsg());
				} else {
					pages = response.getPage();
					totaPages = response.getTotalPage();
					ArrayList<OItem> OitemArr = response.getPostArray();
					if (OitemArr != null) {
						for (OItem oi : OitemArr) {
							list_Oitems.add(oi);
						}
					}

					if (pages == totaPages) {

						if (lv_items.getFooterViewsCount() != 0)
							lv_items.removeFooterView(footerView);
						lv_items.setFooterDividersEnabled(true);

					} else {
						footerView.setVisibility(View.VISIBLE);
						lv_items.setFooterDividersEnabled(true);
						if (lv_items.getFooterViewsCount() == 0)
							lv_items.addFooterView(footerView);
					}

					txtshowmore.setText("Showing " + pages + " of " + totaPages
							+ " pages");
					listoitemadapter.notifyDataSetChanged();

					if (list_Oitems.size() == 0)
						noResults.setVisibility(View.VISIBLE);
				}

			} else {
				CommonHelper.showWarning(getParent(),
						getString(R.string.loaddatastate));

			}

		};
	};

	public GetPostListResponse callService() {
		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_GET_POST_LIST);
		userRequest.addProperty("user_id", CommonHelper.getUserLogin(this)
				.getId());
		userRequest.addProperty("category_id", post_category);
		userRequest.addProperty("page", pages);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_GET_POST_LIST);
		request.addProperty(GlobalVariables.WS_METHOD_GET_POST_LIST,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_GET_POST_LIST, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_GET_POST_LIST, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}
		return new GetPostListResponse(results);
	}

	public GetPostListResponse callServiceSearch() {
		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_SEARCH_POST_LIST);
		userRequest.addProperty("user_id", CommonHelper.getUserLogin(this)
				.getId());
		userRequest.addProperty("category_id", post_category);
		userRequest.addProperty("page", pages);
		userRequest.addProperty("keyword", keyword);
		userRequest.addProperty("from", price_from);
		userRequest.addProperty("to", price_to);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_SEARCH_POST_LIST);
		request.addProperty(GlobalVariables.WS_METHOD_SEARCH_POST_LIST,
				userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_SEARCH_POST_LIST, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_SEARCH_POST_LIST, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}
		return new GetPostListResponse(results);
	}

	public void doSearch() {
		pages = 1;
		list_Oitems.removeAll(list_Oitems);
		if (CommonHelper.isNetworkAvailable(this)) {
			startCallServiceSearch();
		} else {
			CommonHelper.showWarning(this, getString(R.string.netstate));
		}

	}

	@Override
	public void onBackPressed() {
		this.finish();
	}

	// Dialog

	private WheelView initWheel(int id, String[] values, View view) {
		WheelView wheel = (WheelView) view.findViewById(id);
		ArrayWheelAdapter<String> adapter = new ArrayWheelAdapter<String>(this,
				values);
		adapter.setTextSize(20);
		wheel.setViewAdapter(adapter);
		wheel.setCurrentItem(1);
		wheel.setCyclic(true);
		wheel.setInterpolator(new AnticipateOvershootInterpolator());

		return wheel;
	}

	public void DialogCategory() {
		LayoutInflater layoutInflater = (LayoutInflater) getParent()
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		final View view = layoutInflater.inflate(R.layout.dialog_wheel, null);
		final WheelView category = initWheel(R.id.wheel_dialog,
				category_list_array, view);

		final Dialog dia = new Dialog(getParent());
		dia.setContentView(view);
		dia.setTitle("Choose category");
		dia.getWindow().setLayout(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);
		dia.setCancelable(false);
		dia.show();

		final Button btn_change = (Button) view.findViewById(R.id.btn_change);
		btn_change.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				post_category = category.getCurrentItem();
				tv_category.setText(category_list_array[post_category]);
				dia.dismiss();
				noResults.setVisibility(View.GONE);
				pages = 1;
				edt_search.setText("");
				list_Oitems.removeAll(list_Oitems);
				initData();
			}
		});
		Button btn_cancel = (Button) view.findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dia.dismiss();

			}
		});
	}

}
